<template>
	<el-dialog v-model="dialogVisible" append-to-body :show-close="false" :close-on-click-modal="false"
		class="flex-align" style="width: 100%;height: 100%;padding: 30px 24px;margin: 0;background: transparent;">
		<template #header>
			<el-card style="width: 100%;height: 100%;" body-style="padding: 0;" shadow="never">
				<template #header>
					<div class="flex-space-between">
						<div>
							<el-text style="font-size: 16px;">
								到货明细
							</el-text>
						</div>
						<div>
							<el-button @click="closeDialog">取消</el-button>
							<!-- <el-button @click="closeDialog">
                保存并继续创建
                <el-icon style="margin-left: 4px;">
                  <ArrowDown />
                </el-icon>
              </el-button> -->
							<el-button type="primary" @click="submitForm(vFormRef)">
								保存
							</el-button>
						</div>
					</div>
				</template>
				<el-scrollbar ref="scrollbarRef" @scroll="handleScroll"
					:style="`height: calc(100vh - 69px - ( 30px + 30px));`">
					<el-form :model="formData" :rules="rules" ref="vFormRef" label-position="top" label-width="50px"
						style="padding: 16px;">
						<el-form-item label="采购到货单" prop="receiptOrder">
							<el-select @clear="selectClear('receiptOrder')" v-model="formData.receiptOrder"
								@change="(value:any)=>selectChange(value,'receiptOrder')" multiple ref="receiptOrder"
								clearable>
								<el-option v-for="item in receiptOrderOption" :key="key" :label="item?.label"
									:value="item?.value">
									<!--  -->
									<div class="flex-align-center">
										<el-icon :color="item?.color">
											<component :is="item?.icon"></component>
										</el-icon>
										<!--  -->
										<el-text style="margin-left: 6px;">{{item?.label}}</el-text>
									</div>
								</el-option>
								<!--  -->
								<template #tag>
									<div style="padding-left: 6px;">
										<div>
											<div class="flex-align-center">
												<el-icon :color="receiptOrderOption[receiptOrderIndex]?.color">
													<component :is="receiptOrderOption[receiptOrderIndex]?.icon">
													</component>
												</el-icon>
												<!--  -->
												<el-text size="small"
													style="margin-left: 6px;">{{receiptOrderOption[receiptOrderIndex]?.label}}</el-text>
											</div>
										</div>
									</div>
								</template>
							</el-select>
						</el-form-item>
						<el-form-item label="到货产品" prop="product">
							<el-select @clear="selectClear('product')" v-model="formData.product"
								@change="(value:any)=>selectChange(value,'product')" multiple ref="product" clearable>
								<el-option v-for="item in productOption" :key="key" :label="item?.label"
									:value="item?.value">
									<!--  -->
									<div class="flex-align-center">
										<el-icon :color="item?.color">
											<component :is="item?.icon"></component>
										</el-icon>
										<!--  -->
										<el-text style="margin-left: 6px;">{{item?.label}}</el-text>
									</div>
								</el-option>
								<!--  -->
								<template #tag>
									<div style="padding-left: 6px;">
										<div>
											<div class="flex-align-center">
												<el-icon :color="productOption[productIndex]?.color">
													<component :is="productOption[productIndex]?.icon">
													</component>
												</el-icon>
												<!--  -->
												<el-text size="small"
													style="margin-left: 6px;">{{productOption[productIndex]?.label}}</el-text>
											</div>
										</div>
									</div>
								</template>
							</el-select>
						</el-form-item>
						<el-form-item label="本次到货数量" prop="receivedQuantity">
							<el-input placeholder="请填写" type="number" v-model="formData.receivedQuantity" clearable></el-input>
						</el-form-item>
						<el-form-item label="采购明细" prop="purchaseDetail">
							<el-select @clear="selectClear('purchaseDetail')" v-model="formData.purchaseDetail"
								@change="(value:any)=>selectChange(value,'purchaseDetail')" multiple
								ref="purchaseDetail" clearable>
								<el-option v-for="item in purchaseDetailOption" :key="key" :label="item?.label"
									:value="item?.value">
									<!--  -->
									<div class="flex-align-center">
										<el-icon :color="item?.color">
											<component :is="item?.icon"></component>
										</el-icon>
										<!--  -->
										<el-text style="margin-left: 6px;">{{item?.label}}</el-text>
									</div>
								</el-option>
								<!--  -->
								<template #tag>
									<div style="padding-left: 6px;">
										<div>
											<div class="flex-align-center">
												<el-icon :color="purchaseDetailOption[purchaseDetailIndex]?.color">
													<component :is="purchaseDetailOption[purchaseDetailIndex]?.icon">
													</component>
												</el-icon>
												<!--  -->
												<el-text size="small"
													style="margin-left: 6px;">{{purchaseDetailOption[purchaseDetailIndex]?.label}}</el-text>
											</div>
										</div>
									</div>
								</template>
							</el-select>
						</el-form-item>
					</el-form>
				</el-scrollbar>
				<!--  -->
			</el-card>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
	import { ElLoading, ElMessage, FormInstance } from 'element-plus';
	import { onMounted, reactive, ref } from 'vue';
	import { useRoute, useRouter } from 'vue-router';
	import request from '../../../utils/request';
	import { UserFilled, WalletFilled, CirclePlus, DocumentAdd, Delete, Van, CopyDocument, UploadFilled, GoodsFilled } from '@element-plus/icons-vue';
	import { mergeObjects, formatNumber } from '../../../utils';
	import { useSelect } from '../../../utils/mixins';
	import levitation from '../../../components/levitation-form/levitation-form.vue';
	import { formatDate } from '../../../utils/date';
	const emits = defineEmits(['update']);
	const { handSelectChange } = useSelect();
	const router = useRouter();
	const route = useRoute();
	const vFormRef = ref(null);
	const loading = ref(false);
	// 表单
	const formData = ref({
		receiptOrderId: null,//采购到货单
		receiptOrder: [],
		productId: null, //到货产品
		product: [],
		receivedQuantity: null,//本次到货数量
		purchaseDetailId: null,//采购明细
		purchaseDetail: [],
	});
	//验证
	const rules = reactive({
		receiptOrder: [{ required: true, message: '不能为空', trigger: 'blur' }],//采购到货单
		product: [{ required: true, message: '不能为空', trigger: 'blur' }],//到货产品
		receivedQuantity: [{ required: true, message: '不能为空', trigger: 'blur' }],//本次到货数量
		purchaseDetail: [{ required: true, message: '不能为空', trigger: 'blur' }],//采购明细
	});
	const pageData = ref({
		pageNum: 1,
		pageSize: 1000,
	});
	//采购到货单
	const receiptOrderOption = ref([]);
	const receiptOrderIndex = ref(-1);
	const receiptOrder = ref(null);
	//到货产品
	const productOption = ref([]);
	const productIndex = ref(-1);
	const product = ref(null);
	//采购明细
	const purchaseDetailOption = ref([]);
	const purchaseDetailIndex = ref(-1);
	const purchaseDetail = ref(null);

	//
	const dialogVisible = ref(false);
	/**
	 * 打开弹出层
	 */
	const openDialog = () => {
		dialogVisible.value = true;
		setTimeout(async () => {
			const result = await getPageId();
			//
			if (result) {
				getreceiptOrderAll();
				getproductAll();
				getpurchaseDetailAll();
			}
		}, 10);
	}
	/**
	 * 关闭弹出层
	 */
	const closeDialog = () => {
		dialogVisible.value = false;
		vFormRef.value.resetFields();
		//清空url参数
		router.push({ query: {} });
	}
	//获取当前页面的数据
	const getPageId = async () => {
		if (!route.query.id) {
			return true;
		}
		const result = await request({
			url: '/demand/selectReceiptDetailByIds',
			params: {
				id: route.query.id
			},
		});
		//
		console.log('getPageId --->', result);
		//
		formData.value = { ...result.data.t };
		//
		return true;
	}
	//改变
	const selectChange = (value : Array<any>, type : string, key : number) => {
		//所有下拉框的配置列表
		const typeList = [{
			type: 'receiptOrder', //哪一个下拉框，根据ref
			option: receiptOrderOption, //下拉列表选项
			indexVar: receiptOrderIndex, //当前选中项
			idVar: 'receiptOrderId', //当前id值
			blurRef: receiptOrder, //ref
		}, {
			type: 'product', //哪一个下拉框，根据ref
			option: productOption, //下拉列表选项
			indexVar: productIndex, //当前选中项
			idVar: 'productId', //当前id值
			blurRef: product, //ref
		}, {
			type: 'purchaseDetail', //哪一个下拉框，根据ref
			option: purchaseDetailOption, //下拉列表选项
			indexVar: purchaseDetailIndex, //当前选中项
			idVar: 'purchaseDetailId', //当前id值
			blurRef: purchaseDetail, //ref
		},];
		//
		handSelectChange(formData, typeList, value, type, key);
	}
	//获取所有采购到货单
	const getreceiptOrderAll = async () => {
		receiptOrderOption.value = [];
		const result = await request({
			url: '/demand/selectPurchaseArrivalAll',
		});
		//
		console.log('getreceiptOrderAll --->', result);
		//
		result.data.t.list.forEach((item : any, key : number) => {
			receiptOrderOption.value.push({
				label: `预计${formatDate(item.requestDate)}到货 | ${item.supplier.supplierShortName}`,
				value: item.arrivalId,
				icon: Van,
				color: '#ff5500'
			});
			if (formData.value.receiptOrderId === item.arrivalId) {
				formData.value.receiptOrder = [item.arrivalId];
				receiptOrderIndex.value = key;
				//
			}
		});
	}
	//获取所有到货产品 
	const getproductAll = async () => {
		
		const result = await request({
			url: '/demand/productAll',
		});
		//
		console.log('getproductAll --->', result);
		//
		const { productList } = result.data.t;
		//
		productOption.value = [];
		productList.forEach((item : any, key : number) => {
			productOption.value.push({
				label: `${item.productName}${item.model} | 在库${item.currentInventory}件`,
				value: item.productId,
				icon: GoodsFilled,
				color: '#5283ff'
			});
			if (formData.value.productId === item.productId) {
				formData.value.product = [item.productId];
				productIndex.value = key;
				//
			}
		});
	}
	//获取所有采购明细
	const getpurchaseDetailAll = async () => {
		purchaseDetailOption.value = [];
		const result = await request({
			url: '/demand/selectPurchaseDetailAll',
		});
		//
		console.log('getorderDetailAll --->', result);
		result.data.t.list.forEach((item : any, key : number) => {
			purchaseDetailOption.value.push({
				label: `${item?.order.purchaseOrderNumber}_${item.product.productName}${item.product.model}`,
				value: item.purchaseDetailId,
				icon: CopyDocument,
				color: '#82b51b'
			});
			if (formData.value?.purchaseDetailId === item.purchaseDetailId) {
				formData.value.purchaseDetail = [item.purchaseDetailId];
				purchaseDetailIndex.value = key;
				//
			}
		});
	}
	//提交表单
	const submitForm = async (formEl : FormInstance | undefined) => {
		if (!formEl) return;
		await formEl.validate(async (valid, fields) => {
			if (valid) {
				console.log('submitForm ---> ', formData.value);
				const data = {...formData.value};
				delete data.product;
				delete data.purchaseDetail;
				delete data.receiptOrder;
				let type = '';
				if (!route.query.id) {
					type = '/addReceiptDetail';
				} else {
					type = '/updateReceiptDetail';
				}
				//
				const result = await request({
					url: '/demand' + type,
					data: data,
					method: 'post'
				});
				//
				console.log('submitForm--->', result);
				//
				if (result.data.code === 200) {
					ElMessage.success({
						message: '操作成功！'
					});
				} else {
					ElMessage.error({
						message: result.data.msg
					});
				}
				// //
				setTimeout(() => {
					closeDialog();
					emits('update');
				}, 1);
			} else {
				//
				console.log('error submit!', fields);
			}
		});
	}
	//
	defineExpose({
		openDialog
	});
</script>
<style>
	@import '../../../assets/css/my-form-item.css';

	.el-scrollbar__view {
		display: block !important;
	}
</style>
<style scoped lang="scss">
	@import '../../../assets/css/index.scss';
</style>